package com.hzhc.controller.sysmanage;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzhc.annotation.SysTemLog;
import com.hzhc.common.BaseController;
import com.hzhc.dto.UserDto;
import com.hzhc.entity.SysYzsRole;
import com.hzhc.entity.UserMember;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.service.SysMemberRoleService;
import com.hzhc.service.SysUserSecurityService;
import com.hzhc.service.UserMemberService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.utils.TokenUtil;
import com.hzhc.vo.CarInfoVo;
import com.hzhc.vo.UserMemberVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dongcy
 * @date 2024/4/8 10:19
 * @description UserMemberController
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/userMember")
public class UserMemberController extends BaseController {

    private final UserMemberService userMemberService;
    private final SysMemberRoleService sysMemberRoleService;
    private final SysUserSecurityService securityService;

    /**
     * 获取客户账号分页列表
     * @param request
     * @param vo
     * @return
     */
    @RequestMapping("/getUserMemberList")
    public ResultUtil<List<UserMemberVo>> getUserList(HttpServletRequest request, @RequestBody UserMemberVo vo) {
        Page<UserMemberVo> page = new Page<UserMemberVo>(vo.getPageIndex(), vo.getPageSize());
        UserDto user =  TokenUtil.getUser(request);
        vo.setUserId(user.getId());
        vo.setCreateTime(LocalDateTime.now());
        List<UserMemberVo> memberList = userMemberService.getUserMemberList(page, vo);
        return ResultUtil.build(memberList,page.getTotal(),page.getPages(), ResultUtilCodeEnum.SUCCESS);
    }

    //检查司机是否为黑名单
    @RequestMapping("/checkIsBlack")
    public ResultUtil<T> checkIsBlack(@RequestBody UserMemberVo vo){
        return userMemberService.checkIsBlack(vo);
    }

    /**
     *  保存客户账号
     * @param request
     * @param data
     * @return
     */
    @PostMapping("/saveUserMember")
    @SysTemLog(operModul = "基础信息-客户账号新增", operType = "新增", operDesc = "客户账号新增功能", modular = "PC")
    public ResultUtil<T> saveUserMember(HttpServletRequest request, @RequestBody JSONObject data) {
        UserMemberVo vo = data.to(UserMemberVo.class);

        LambdaQueryWrapper<UserMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMember::getUsername,vo.getTelephone())
                .eq(UserMember::getDisable,0);

        UserMember one = userMemberService.getOne(wrapper);
        boolean flag = true;
        if (one==null){//没有则新增
            String field = "username";
            String username = data.getString("username");
            Boolean bool1 = userMemberService.checkUserMemberByField(field, username,null);
            if (bool1) {
                return ResultUtil.build(ResultUtilCodeEnum.LOGIN_NAME_AlREAD_EXIST);
            }
            String field1 = "telephone";
            String telephone = data.getString("telephone");
            Boolean bool2 = userMemberService.checkUserMemberByField(field1, telephone, null);
            vo.setUsername(telephone);
            if (bool2) {
                vo.setUsername(telephone);
            }
            //客户账号 密码java正则校验  开始
            ResultUtil<T> rel = securityService.checkPasswordLevel(vo.getRealPassword());
            if (rel.getCode()==400){
                return rel;
            }
            //客户账号 密码java正则校验  结束
            vo.setFleet(vo.getFleet());//车队id
            vo.setCompanyId(null);//公司id
            if(vo.getInoutflag()!=null){
                vo.setInoutflag(vo.getInoutflag());
            }else{
                vo.setInoutflag(0);//扫码默认外部
            }
            boolean bool  = userMemberService.saveUserMember(vo);
            flag = false;
        }else{//有则更新信息+加入新车队
            userMemberService.updateDriver(vo);
            flag = false;
        }
        if(!flag){
            return ResultUtil.ok();
        }else{
            return ResultUtil.fail();
        }
    }
    /**
     * 编辑
     */
    @RequestMapping("/userMemberUpdate")
    @SysTemLog(operModul = "基础信息-客户账号编辑", operType = "编辑", operDesc = "客户账号编辑功能", modular = "PC")
    public ResultUtil<T> updateUserMember(HttpServletRequest request,  @RequestBody JSONObject data) {
        UserMemberVo vo = data.to(UserMemberVo.class);
        UserDto user = TokenUtil.getUser(request);
        vo.setUpdateUserId(user.getId().longValue());
        boolean bool = userMemberService.updateUserMember(vo);
        if (bool){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    /**
     * 删除
     */
    @RequestMapping("/userMemberDel")
    @SysTemLog(operModul = "基础信息-客户账号删除", operType = "删除", operDesc = "客户账号删除功能", modular = "PC")
    public ResultUtil<T> userMemberDel(HttpServletRequest request, Model model, @RequestBody JSONObject data) {
        String token = request.getHeader("token");
        UserMemberVo vo = data.to(UserMemberVo.class);
        boolean bool = userMemberService.userMemberDelete(vo);
        if (bool){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    /**
     *  检测客户账号手机号
     * @param request
     * @param data
     * @return
     */
    @RequestMapping("/checkUserMemberMobile")
    public ResultUtil<T> checkUserMemberMobile(HttpServletRequest request, @RequestBody JSONObject data) {
        String field = "telephone";
        String msg = "";
        Integer id = null;
        String companyName= data.getString("companyName");
        String mobile = data.getString("telephone");
        if (data.containsKey("id")) {
            id = data.getInteger("id");
        }
        Boolean bool = userMemberService.checkDriverByField(field, mobile, id,companyName);
        if (bool) {
            return ResultUtil.build(ResultUtilCodeEnum.MOBILE_AlREAD_EXIST);
        }
        return ResultUtil.ok();
    }

    /**
     * 校验账号是否存在
     * @param request
     * @param userMember
     * @return
     */
    @RequestMapping("/getUserName")
    public ResultUtil<T> getRoleCode(HttpServletRequest request, @RequestBody UserMember userMember){
        Boolean bool = false;
        if(userMember.getId()!=null){
            bool = userMemberService.checkUserMemberByField("username", userMember.getUsername(),userMember.getId().intValue());
        }else{
            bool = userMemberService.checkUserMemberByField("username", userMember.getUsername(),null);
        }
        if (bool) {
            return ResultUtil.build(ResultUtilCodeEnum.LOGIN_NAME_AlREAD_EXIST);
        }else{
            return ResultUtil.ok();
        }
    }

    /**
     * 重置密码
     * @param userMember
     * @return
     */
    @PostMapping("/resetPasswd")
    @SysTemLog(operModul = "基础信息-客户账号重置密码", operType = "重置密码", operDesc = "客户账号重置密码功能", modular="PC")
    public ResultUtil<T> resetPasswd(HttpServletRequest request,@RequestBody UserMember userMember) {
        String token = request.getHeader("token");
        boolean bool = userMemberService.resetPasswd(userMember);
        if(bool){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    /**
     * 获取用户角色
     * @param request
     * @param data
     * @return
     */
    @RequestMapping("/getYzsRoleByMemberId")
    public ResultUtil<List<SysYzsRole>> getYzsRoleByMemberId(HttpServletRequest request, @RequestBody JSONObject data) {
        Integer uid = data.getInteger("id");
        Long id = Long.valueOf(uid);
        return ResultUtil.build(sysMemberRoleService.getYzsRoleByMemberId(id),ResultUtilCodeEnum.SUCCESS);
    }

    /**
     ** 更新用户角色
     *
     * @param request
     * @param data
     * @return
     */
    @SuppressWarnings("unchecked")
    @PostMapping("/yzsRoleSave")
    @SysTemLog(operModul = "系统管理-用户管理修改用户角色", operType = "修改用户角色", operDesc = "用户管理修改用户角色功能", modular="PC")
    public ResultUtil<T> yzsRoleSave(HttpServletRequest request, @RequestBody JSONObject data) {
        int userid = data.getInteger("id");
        List<Integer> roleids = (ArrayList<Integer>) data.get("roleIds");
        Boolean bool  = sysMemberRoleService.saveYzsRole(userid, roleids);
        if(bool){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }
    /**
     * 司机导入
     * 保存上传的司机
     */
    @PostMapping("/importDriverList")
    public ResultUtil<T> importCarList(HttpServletRequest request, @RequestBody UserMemberVo vo) {
        return userMemberService.importDriverList(request, vo.getDrivers());
    }
    /**
     * 司机清单导出模板下载
     */
    private final static String EXPORT_EXCEL_PATH_CMS = "static/download/司机导入.xlsx";

    @GetMapping("/exportDriverFile")
    public void exportCarFile(HttpServletRequest request, HttpServletResponse response) {
        userMemberService.exportDriverFile(request, response, EXPORT_EXCEL_PATH_CMS);
    }

    /**
     *司机导入上传
     */
    @RequestMapping("/driverUpload")
    public ResultUtil<List<UserMemberVo>> carUpload(MultipartFile file, HttpServletRequest request) {
        UserDto user = TokenUtil.getUser(request);
        return userMemberService.DriverUpload(user,file);
    }
    //车辆预约 add 司机下拉框
    @RequestMapping("/getDriverList")
    public ResultUtil<List<UserMemberVo>> getDriverList(@RequestBody UserMemberVo vo){
        List<UserMemberVo> list = userMemberService.getYzsDriverList(vo);
        return ResultUtil.build(list,ResultUtilCodeEnum.SUCCESS);
    }
    /**
     * 手机号匹配司机信息
     */
    @RequestMapping("/getDriver")
    public ResultUtil<List<UserMember>> getDriver(@RequestBody UserMemberVo vo) {
        List<UserMember> list = userMemberService.getDriver(vo.getTelephone());
        return ResultUtil.build(list, ResultUtilCodeEnum.SUCCESS);
    }


    /**
     * 解锁
     * @param userMember
     * @return
     */
    @PostMapping("/unlockRet")
    @SysTemLog(operModul = "基础信息-客户账号解锁", operType = "解锁", operDesc = "客户账号解锁功能", modular="PC")
    public ResultUtil<T> unlockRet(@RequestBody UserMember userMember) {
        boolean bool = userMemberService.unlockRet(userMember);
        if(bool){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }
}
